package br.mg.bhe.ftpobre.command;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.net.ftp.FTPSClient;

import br.mg.bhe.ftpobre.Main;
import br.mg.bhe.ftpobre.gui.MainFrame;
import br.mg.bhe.ftpobre.log.FtpLogView;
import br.mg.bhe.ftpobre.util.LocalFileUtil;
import br.mg.bhe.ftpobre.util.LogUtil;

/**
 * 
 * @author Aureliano
 */
public class UploadCommand implements ICommand {

	private static final Logger logger = LogUtil.getLogger(UploadCommand.class);
	
	@Override
	public void execute() {
		if (this.canExecute()) {
			this.doAction();
		}
	}

	@Override
	public boolean canExecute() {
		return ((LocalFileUtil.getSelectedFile() != null) && Main.getConnectionData().isConnected());
	}

	private void doAction() {
		String workingDirectory = MainFrame.getInstance().getAbsolutePathFromRemoteFilePath();
		FTPSClient ftp = (FTPSClient) Main.getConnectionData().getFtpClient();
		
		try {
			FtpLogView.log("Definindo diretório '" + workingDirectory + "' como destino no Servidor FTP");
			
			String fileName = this.getUploadCandidateFileName();
			ftp.storeFile(workingDirectory + "/" + fileName, this.getUploadCandidateFileStream());
			
			FtpLogView.log("Arquivo '" + fileName + "' enviado com sucesso!");
			CommandFactory.command(RefreshRemoteFilesViewCommand.class).execute();
		} catch (IOException ex) {
			logger.log(Level.SEVERE, ex.getMessage(), ex);
			FtpLogView.log("Não foi possível fazer upload de arquivo para Servidor FTP. Detalhe: " + ex.getMessage());
			throw new RuntimeException(ex);
		}
	}
	
	private FileInputStream getUploadCandidateFileStream() throws FileNotFoundException {	
		return new FileInputStream(LocalFileUtil.getSelectedFile().getPath());
	}
	
	private String getUploadCandidateFileName() {
		return LocalFileUtil.getSelectedFile().getName();
	}
}